import { defineComponent, reactive, ref } from 'vue'
import { Button, Form, Input, message } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'

export interface loginInfo {
  loginEmail: string
  password: string
}

export default defineComponent({
  name: 'login',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const ruleForm = ref<any>(null)

    const data = reactive({
      labelCol: { span: 5 },
      wrapperCol: { span: 15 }
    })

    const tailFormItemLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0, },
        sm: { span: 16, offset: 8, },
      },
    }

    const modelRef = reactive({
      loginEmail: '',
      password: ''
    })

    const rulesRef = reactive({
      loginEmail: [
        { required: true, message: '请输入登录邮箱', trigger: 'blur' },
        { message: '请输入正确的邮箱', type: 'email', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'change' }
      ]
    })

    // 所有验证都通过的情况走这里，相当于提交
    const onFinish = async (loginInfo: loginInfo) => {
      const userData = await store.dispatch('user/login', loginInfo)
      if (!userData.success) {
        return message.error(userData.msg)
      }
      await router.push(route.query.redirect as string || 'homeList')
      location.reload()
    }

    return () => (
      <div class='register-form'>
        <Form
          ref={ruleForm}
          name="control-ref"
          labelCol={data.labelCol}
          wrapperCol={data.wrapperCol}
          model={modelRef}
          rules={rulesRef}
          onFinish={onFinish}
        >
          <Form.Item
            name="loginEmail"
            label="邮箱"
            hasFeedback
          >
            <Input v-model={[modelRef.loginEmail, 'value']} type="email" placeholder='请输入邮箱'/>
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            hasFeedback
          >
            <Input.Password v-model={[modelRef.password, 'value']} type="password" placeholder='请输入密码'/>
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
  }
})
